#!/bin/bash

# there're two cache space in sed:
#   - Pattern Space: saves the current line to be edit, readed from the input file 
#   
#   - Hold Space: additional buffer avaliable where sed can hold temporary data.
#       sed allows user to move date back and forth between pattern space and hold space. 
#       we cannot execute the typical sed commands on the hold space. 

# this scripts will modify test_empnametitle.txt


# - swap pattern space with hold space using 'x' command 
sed -n -e 'x;n' -e '/Manager/{x;p}' ./test_empnametitle.txt
echo -e '\n'
#   * x;n : 'x' swap contents of pattern space to hold sapce, n reads the next line into
#           the pattern space. 
#
#           In this example sed saves the employee name to hold space and fetch imployee 
#           title into pattern space 
#
#   * /Manager/{x;p}: if the content of the pattern space contains keyword 'Manager', sed 
#           swaps pattern space with hold space and prints pattern space.
#
#   * the result of command is: if the employee title contains "Manager", the employee
#     name will be printed.
#
#     Especially suite for output the line that before the test line.


# -- copy pattern space to hold space using 'h' command
sed -n -e '/Manager/!h' -e '/Manager/{x;p}' ./test_empnametitle.txt
echo -e '\n'
#   * /Manager/!h : if the content of pattern space doesn't contain keyword "Manager"
#           (! is identical to 'not euqal to'), copy the content of pattern space to 
#           hold space.


# -- append pattern space to hold space using 'H' command 
#  - print the name and title of the managers in seperate line 
sed -n -e '/Manager/!h' -e '/Manager/{H;x;p}' ./test_empnametitle.txt
echo -e '\n'
#   * /Manager/!h : let sed matches the line doesn't contain 'Manager' in pattern space
#       and copy it from pattern space to hold sapce. this operation makes all names and 
#       titles that not contain manager into Hold space.
#   
#   * /Manager/{H;x;p} : if the content of pattern space contains the keyword 'Manager',
#       H command let sed append it from pattern space to hold space. then exchange
#       hold space with pattern space, and print pattern space at the end.


# -- copy hold space to pattern space using 'g' command 
#  - print the names of the managers
sed -n -e '/Manager/!h' -e '/Manager/{g;p}' ./test_empnametitle.txt
echo -e '\n'
#   * '/Manager/!h' : matches all lines that don't contain keyword 'Manager' copy it to 
#       hold space, then sed reads next line into pattern space.
#
#   * '/Manager/{g;p}' : if current line in pattern space contains 'Manager' copy hold
#       space (the name of Manager) into pattern space, then print pattern space.



# -- append hold space to pattern space using 'G' command
#  - prints the employee name and title of the manager separated by colon
sed -n -e '/Manager/!h' -e '/Manager/{x;G;s/\n/:/;p}' ./test_empnametitle.txt
echo -e '\n'
